package com.imageflowpro.image_flow_pro.service.impl;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.imageflowpro.image_flow_pro.constant.JwtClaimsConstant;
import com.imageflowpro.image_flow_pro.context.BaseContext;
import com.imageflowpro.image_flow_pro.exception.BaseException;
import com.imageflowpro.image_flow_pro.po.MediaOrder;
import com.imageflowpro.image_flow_pro.po.OrderComment;
import com.imageflowpro.image_flow_pro.mapper.OrderCommentMapper;
import com.imageflowpro.image_flow_pro.po.User;
import com.imageflowpro.image_flow_pro.service.IOrderCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * <p>
 * 订单注释记录 服务实现类
 * </p>
 *
 * @author 张家浩
 * @since 2025-05-07
 */
@Service
public class OrderCommentServiceImpl extends ServiceImpl<OrderCommentMapper, OrderComment> implements IOrderCommentService {

    @Override
    @Transactional
    public OrderComment adminSaveOrUpdateComment(OrderComment orderComment) {
        if(orderComment.getOrderId()==null){
            throw new BaseException("没有指定订单");
        }
        boolean exists = Db.lambdaQuery(MediaOrder.class)
                .eq(MediaOrder::getId, orderComment.getOrderId())
                .exists();
        if(!exists){
            throw new BaseException("订单不存在");
        }
        orderComment.setAdminId(BaseContext.getCurrentId());
        if(orderComment.getId()!=null){
            OrderComment byId = this.getById(orderComment.getId());
            if(!Objects.equals(byId.getAdminId(), BaseContext.getCurrentId())){
                throw new BaseException("只能修改自己的评论");
            }
            this.updateById(orderComment);
            return orderComment;
        }
        this.save(orderComment);
        return orderComment;
    }

    @Override
    @Transactional
    public void adminDeleteComment(Long commentId) {
        OrderComment comment = this.getById(commentId);
        if(comment==null){
            throw new BaseException("评论不存在");
        }
        if(!Objects.equals(comment.getAdminId(), BaseContext.getCurrentId())){
            User user = Db.lambdaQuery(User.class)
                    .eq(User::getId, BaseContext.getCurrentId())
                    .one();
            if (!JwtClaimsConstant.SUPER_ADMIN_ROLE.equals(user.getRole())){
                throw new BaseException("只能删除自己的评论");
            }
        }
        this.removeById(commentId);
    }
}
